package permission

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/predicate"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserPhoneUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserPhoneUpdateLogic - 用户修改手机号
func NewAdminUserPhoneUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserPhoneUpdateLogic {
	return &AdminUserPhoneUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserPhoneUpdateLogic) AdminUserPhoneUpdate(req *types.AdminUserPhoneUpdateRequest) error {
	userDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	// 查询用户
	adminUserCond := make([]predicate.AdminUser, 0, 2)
	adminUserCond = append(adminUserCond, adminuser.AdminUserUsernameEQ(req.AdminUserPhone))
	adminUserCond = append(adminUserCond, adminuser.IsDeleteEQ(bizadmin.NotDelete))
	adminUser, err := userDao.AdminUserFirst(adminUserCond)
	if err != nil && !ent.IsNotFound(err) {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户失败：%v", err.Error()))
	}

	// 检验手机号是否存在
	if req.OperateType == bizadmin.PhoneTypeOld {
		if adminUser == nil || ent.IsNotFound(err) {
			return xerr.ErrCodeMsg(xerr.ServerAdminUserPhoneNotExist, "手机号不存在")
		}
	} else {
		if adminUser != nil {
			return xerr.ErrCodeMsg(xerr.ServerAdminUserPhoneHasExist, "手机号已被占用")
		}

		// 查询当前用户信息
		userId := common.JwtAdminAuthUserId(l.ctx)
		adminUserCond = make([]predicate.AdminUser, 0, 2)
		adminUserCond = append(adminUserCond, adminuser.IDEQ(int(userId)))
		adminUserCond = append(adminUserCond, adminuser.IsDeleteEQ(bizadmin.NotDelete))
		adminUser, err = userDao.AdminUserFirst(adminUserCond)
		if err != nil {
			if ent.IsNotFound(err) {
				return xerr.ErrCodeMsg(xerr.ServerAdminUserNotExist, "用户不存在")
			}
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查不到当前用户：%v", err.Error()))
		}

		// 校验用户
		if adminUser.AdminUserStatus == bizadmin.StatusDisable {
			return xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用")
		}
	}

	// 校验验证码
	err = handleCheckCaptchaFromRedis(l.svcCtx.BizRedis, l.ctx, constant.HzAdminLoginCaptchaKey+req.AdminUserPhone, req.AdminUserCaptcha)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerAdminSMSCodeError, fmt.Sprintf("验证码校验失败，%v", err.Error()))
	}

	// 新手机号，更新
	if req.OperateType == bizadmin.PhoneTypeNew {
		adminUser.AdminUserUsername = req.AdminUserPhone
		err = userDao.AdminUserUpdate(adminUser, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("更新手机号失败：%v", err.Error()))
		}
	}

	return nil
}
